package es.unex.meigas.gui;

import java.awt.Color;
import java.awt.Graphics;
import java.awt.geom.Rectangle2D;
import java.util.ArrayList;

import javax.swing.JPanel;

import es.unex.meigas.core.DasocraticElement;

public class SimpleViewPanel extends JPanel {

	public static final int MARGIN = 15;
	private World2Device m_W2D;
	private ArrayList m_Elements = new ArrayList();

	public SimpleViewPanel(){

		super();

		this.setBackground(Color.white);

	}

	public void addElement(DasocraticElement element){

		m_Elements.add(element);

	}

	public void paint( Graphics g ) {

		super.paint(g);

		int i;

		recalculateExtent();

		for (i = 0; i < m_Elements.size(); i++){
			paintElement(g, (DasocraticElement) m_Elements.get(i));
		}

	}

	private void paintElement(Graphics g, DasocraticElement element) {

		element.paint(g, m_W2D);

	}

	private void recalculateExtent(){

		int i;
		double dMinX = Double.MAX_VALUE;
		double dMaxX = Double.NEGATIVE_INFINITY;
		double dMinY = Double.MAX_VALUE;
		double dMaxY = Double.NEGATIVE_INFINITY;
		double dRangeX, dRangeY;
		double dWidth, dHeight;
		double dDif;
		double dScale;
		Rectangle2D rect;
		DasocraticElement element;

		for (i = 0; i < m_Elements.size(); i++){
			element = (DasocraticElement)m_Elements.get(i);
			rect = element.getBoundingBox();
			if (rect != null){
				dMinX = Math.min(rect.getMinX(), dMinX);
				dMinY = Math.min(rect.getMinY(), dMinY);
				dMaxX = Math.max(rect.getMaxX(), dMaxX);
				dMaxY = Math.max(rect.getMaxY(), dMaxY);
			}
		}

		dRangeX = dMaxX- dMinX;
		dRangeY = dMaxY- dMinY;
		dWidth = getWidth() - 2 * MARGIN;
		dHeight = getHeight() - 2 * MARGIN;
		double dRatioWorld = dRangeX / dRangeY;
		double dRatioCell = dWidth / dHeight;

		m_W2D = new World2Device();

		if (dRatioWorld > dRatioCell){
			dScale = dWidth / dRangeX;
			dDif = (dHeight / dScale - dRangeY) / 2.;
			m_W2D.setXMin(dMinX);
			m_W2D.setYMax(dDif + dMaxY);
		}
		else{
			dScale = dHeight / dRangeY;
			dDif = (dWidth / dScale - dRangeX) / 2.;
			m_W2D.setXMin(dMinX - dDif);
			m_W2D.setYMax(dMaxY);
		}

		m_W2D.setScale(dScale);

	}

}
